package com.ruoyi.demo.controller;

import com.jcraft.jsch.*;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.FileInputStream;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/demo/capture")
public class VideoCaptureController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(JupyterController.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    // SSH 配置
    private static final String SSH_HOST = "192.168.137.2";
    private static final int SSH_PORT = 22;
    // 替换为实际用户名
    private static final String SSH_USERNAME = "root";
    // 替换为实际密码
    private static final String SSH_PASSWORD = "Mind@123";

    // Python 脚本路径
    private static final String PYTHON_SCRIPT = "/home/HwHiAiUser/samples/notebooks/Recording/VideoCapture.py";

    //打开识别接口
    @GetMapping("/open")
    public AjaxResult record(@RequestParam("duration") int duration) {
        Session session = null;
        Channel channel = null;

        try {
            log.info("开始识别 - 时长: {}秒", duration);

            JSch jsch = new JSch();
            session = jsch.getSession(SSH_USERNAME, SSH_HOST, SSH_PORT);
            session.setPassword(SSH_PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(30000);

            channel = session.openChannel("exec");
            String command = String.format(
                    "source /usr/local/miniconda3/bin/activate base && " +
                            "/usr/local/miniconda3/bin/python %s %d",
                    PYTHON_SCRIPT, duration
            );
            log.info("执行命令: {}", command);
            ((ChannelExec) channel).setCommand(command);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            channel.setOutputStream(outputStream);
            ((ChannelExec) channel).setErrStream(errorStream);

            channel.connect();

            while (!channel.isClosed()) {
                Thread.sleep(100);
            }

            String output = outputStream.toString();
            String error = errorStream.toString();

            log.info("Python输出: {}", output);
            log.info("Python错误: {}", error);
            log.info("退出码: {}", ((ChannelExec) channel).getExitStatus());

            if (!error.isEmpty() && !error.contains("WARN") && !error.contains("ERROR:0")) {
                return AjaxResult.error("开启识别失败：" + error);
            }

            if (!output.isEmpty()) {
                String[] lines = output.split("\n");
                String lastValidJson = null;
                for (String line : lines) {
                    if (line.trim().startsWith("{")) {
                        lastValidJson = line.trim();
                    }
                }

                if (lastValidJson != null) {
                    JsonNode resultJson = objectMapper.readTree(lastValidJson);
                    if (resultJson.has("error")) {
                        return AjaxResult.error(resultJson.get("error").asText());
                    }
                    return AjaxResult.success("开启识别成功", resultJson);
                }
            }

            return AjaxResult.error("开启识别失败：未获取到输出");

        } catch (Exception e) {
            log.error("开启识别失败", e);
            return AjaxResult.error("开启识别失败：" + e.getMessage());
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}